//
//  PushViewController.m
//  XMAuto
//
//  Created by lishi on 2019/4/8.
//  Copyright © 2019 lishi. All rights reserved.
//

// 约束(Autolayout)

// Libs
#import "Masonry.h"

#import "PushViewController.h"

#import "AppDelegate.h"

@interface PushViewController ()
<
    UINavigationControllerDelegate
>

@property (nonatomic, strong) UIView *testView;


@property (nonatomic, assign, getter=isallowHor) BOOL allowHor;

//@property (nonatomic, strong) NSLayoutConstraint *constant;

@end

@implementation PushViewController

//- (void)viewDidDisappear:(BOOL)animated {
//    [super viewDidDisappear:animated];
//    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    appDelegate.allowRotation = NO;
//}
//
//- (void)viewDidAppear:(BOOL)animated {
//    [super viewDidAppear:animated];
//    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    appDelegate.allowRotation = YES;
//}

//-(void)viewDidAppear:(BOOL)animated{
//    [super viewDidAppear:animated];
//    //开始生成 设备旋转 通知
//    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
//
//    //添加 设备旋转 通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
//}
//
///**屏幕旋转的通知回调*/
//- (void)orientChange:(NSNotification *)noti {
//    UIDeviceOrientation orient = [UIDevice currentDevice].orientation;
//    switch (orient) {
//        case UIDeviceOrientationPortrait:
////            self.allowHor = NO;
//            NSLog(@"竖直屏幕");
//            break;
//        case UIDeviceOrientationLandscapeLeft:
//            NSLog(@"手机左转");
////            self.allowHor = YES;
//            break;
//        case UIDeviceOrientationPortraitUpsideDown:
//            NSLog(@"手机竖直");
//            break;
//        case UIDeviceOrientationLandscapeRight:
//            NSLog(@"手机右转");
////            self.allowHor = YES;
//            break;
//        case UIDeviceOrientationUnknown:
//            NSLog(@"未知");
//            break;
//        case UIDeviceOrientationFaceUp:
//            NSLog(@"手机屏幕朝上");
//            break;
//        case UIDeviceOrientationFaceDown:
//            NSLog(@"手机屏幕朝下");
//            break;
//        default:
//            break;
//    }
//}


//- (void)viewDidDisappear:(BOOL)animated{
//    [super viewDidDisappear:animated];
//    //销毁 设备旋转 通知
//    [[NSNotificationCenter defaultCenter] removeObserver:self
//                                                    name:UIDeviceOrientationDidChangeNotification
//                                                  object:nil
//     ];
//    //结束 设备旋转通知
//    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
//
//}

//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
//        NSLog(@"clicked navigationbar back button");
//        [self forceOrientation:UIInterfaceOrientationPortrait];
//    }
//}

- (void)backClick:(UIBarButtonItem *)item {
    if (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation)) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self forceOrientation:UIInterfaceOrientationPortrait];
    }
}

- (void)pushClick:(UIBarButtonItem *)item {
    if (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation)) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    } else {
        [self forceOrientation:UIInterfaceOrientationPortrait];
    }
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backClick:)];
    self.navigationItem.leftBarButtonItem = leftButton;
    
    // 强制横屏显示
    [self forceOrientation:UIInterfaceOrientationLandscapeRight];
}

- (void)forceOrientation:(UIInterfaceOrientation)orientation {
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget: [UIDevice currentDevice]];
        int val = orientation;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator: coordinator];
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
//        if (self.isallowHor == YES) {
//            [self.testView setFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 200)];
//        } else {
//            [self.testView setFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];
//        }
        // 设备方向
//        UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
//        if (UIDeviceOrientationIsLandscape(deviceOrientation)) {
//            NSLog(@"横向");
//            [self.testView mas_remakeConstraints:^(MASConstraintMaker *make) {
//                make.top.left.bottom.right.mas_equalTo(self.view).offset(0);
//            }];
//        } else {
//            NSLog(@"纵向");
//            [self.testView mas_remakeConstraints:^(MASConstraintMaker *make) {
//                make.top.left.right.mas_equalTo(self.view).offset(0);
//                make.height.offset(200);
//            }];
//        }
        
        // 状态栏方向
        UIInterfaceOrientation statusBarOrientation = [UIApplication sharedApplication].statusBarOrientation;
        if (UIInterfaceOrientationIsPortrait(statusBarOrientation)) {
            [self.testView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.left.right.mas_equalTo(self.view).offset(0);
                make.height.offset(200);
            }];
        } else {
            [self.testView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.left.bottom.right.mas_equalTo(self.view).offset(0);
            }];
        }
        [self.view layoutIfNeeded];
    } completion: ^(id<UIViewControllerTransitionCoordinatorContext> context) {
        
    }];
    NSLog(@"size.width == %f",size.width);
    NSLog(@"%ld",(long)[UIApplication sharedApplication].statusBarOrientation);
    NSLog(@"%ld",(long)self.interfaceOrientation);
}

//- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
//    NSLog(@"%s",__func__);
//    if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
//        [self.testView setFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 200)];
//    }
//    else {
//        [self.testView setFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];
//    }
//}

//- (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection
//              withTransitionCoordinator:(id )coordinator {
//    [super willTransitionToTraitCollection:newCollection
//                 withTransitionCoordinator:coordinator];
//    [coordinator animateAlongsideTransition:^(id  context) {
//        if (newCollection.verticalSizeClass == UIUserInterfaceSizeClassCompact) {
//            NSLog(@"UIUserInterfaceSizeClassCompact");
//        } else {
//
//        }
//        [self.view setNeedsLayout];
//    } completion:nil];
//}

- (BOOL)prefersStatusBarHidden {
    return NO;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationFade;
}

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

//- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
//    return UIInterfaceOrientationLandscapeRight;
//}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}

- (void)dealloc {
    self.navigationController.delegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.allowHor = NO;
    
    self.navigationController.delegate = self;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self.view addSubview:self.testView];
    [self.testView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view).offset(0);
        make.height.offset(200);
    }];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor blueColor];
    [btn addTarget:self action:@selector(pushClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(100, 40));
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    
//    [self.testView mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(self.view).offset(200);
//    }];
//
//    [self.view setNeedsUpdateConstraints];
//    [self.view updateConstraintsIfNeeded];
//    [UIView animateWithDuration:2 animations:^{
//        [self.view layoutIfNeeded];
//    } completion:^(BOOL finished) {
//        [self.testView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(self.view).offset(0);
//        }];
//        [self.view setNeedsUpdateConstraints];
//        [self.view updateConstraintsIfNeeded];
//        [UIView animateWithDuration:2 animations:^{
//            [self.view layoutIfNeeded];
//        } completion:^(BOOL finished) {
//
//        }];
//    }];
    
//    [UIView animateWithDuration:2 animations:^{
//        self.testView.transform = CGAffineTransformMakeTranslation(0, 200);
//    } completion:^(BOOL finished) {
//        [UIView animateWithDuration:2 animations:^{
//            self.testView.transform = CGAffineTransformIdentity;
//        } completion:^(BOOL finished) {
//        }];
//    }];
}


- (UIView *)testView {
    if (!_testView) {
        _testView = [[UIView alloc] init];
        _testView.backgroundColor = [UIColor redColor];
    }
    return _testView;
}

@end
